package com.zbs.framework.pay.service.impl;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePrecreateModel;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.zbs.framework.common.utils.ErrorAssert;
import com.zbs.framework.pay.config.AliPayConfig;
import com.zbs.framework.pay.qrcode.QrCodeResponse;
import com.zbs.framework.pay.qrcode.QrResponse;
import com.zbs.framework.pay.service.AliPayService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;

/**
 * @Author Zbs
 * @since 2021/5/24 0024 16:19
 */
@Transactional
@Service
public class AliPayServiceImpl implements AliPayService {

    @Override
    public QrCodeResponse aliPay(String subject, String tradeNo, BigDecimal totalAmount, String express) {
        try {
            ErrorAssert.trimHasLength(subject,"产品标题不能为空");
            ErrorAssert.notNull(totalAmount,"支付金额不能为空");
            ErrorAssert.trimHasLength(express,"支付超时时间不能为空");
            ErrorAssert.trimHasLength(tradeNo,"订单号不能为空");

            AlipayTradePrecreateModel model = new AlipayTradePrecreateModel();
            model.setOutTradeNo(tradeNo); // 自定义订单号
            model.setTotalAmount(totalAmount.toPlainString());// 支付金额
            model.setSubject(subject);// 支付的产品名称
            model.setTimeoutExpress(express);// 支付的超时时间
            return qrcodePay(model);
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    /**
     * 扫码运行代码
     * 验签通过返回QrResponse
     * 失败打印日志信息
     * 参考地址：https://opendocs.alipay.com/apis/api_1/alipay.trade.app.pay
     *
     * @param model
     * @return
     */
    public QrCodeResponse qrcodePay(AlipayTradePrecreateModel model) {
        // 1: 获取阿里请求客户端
        AlipayClient alipayClient = getAlipayClient();
        // 2: 获取阿里请求对象
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        // 3：设置请求参数的集合，最大长度不限
        request.setBizModel(model);
        // 设置异步回调地址
        request.setNotifyUrl(AliPayConfig.notifyUrl);
        // 设置同步回调地址
        request.setReturnUrl(AliPayConfig.returnUrl);
        AlipayTradePrecreateResponse alipayTradePrecreateResponse = null;
        try {
            alipayTradePrecreateResponse = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        QrResponse qrResponse = JSON.parseObject(alipayTradePrecreateResponse.getBody(), QrResponse.class);
        return qrResponse.getAlipay_trade_precreate_response();
    }


    /**
     * 获取AlipayClient对象
     *
     * @return
     */
    private AlipayClient getAlipayClient() {
        if (StringUtils.hasLength(AliPayConfig.encryptKey)) {
            return new DefaultAlipayClient(AliPayConfig.gatewayUrl, AliPayConfig.appId, AliPayConfig.merchantPrivateKey,
                    "JSON", StandardCharsets.UTF_8.name(), AliPayConfig.alipayPublicKey, AliPayConfig.signType,AliPayConfig.encryptKey,"");
        }
        return new DefaultAlipayClient(AliPayConfig.gatewayUrl, AliPayConfig.appId, AliPayConfig.merchantPrivateKey,
                "JSON", StandardCharsets.UTF_8.name(), AliPayConfig.alipayPublicKey, AliPayConfig.signType);
    }
}
